import React, { PureComponent, Fragment } from 'react';

import { connect } from 'dva';

import moment from 'moment';

import QueueAnim from 'rc-queue-anim';
import TweenOne from 'rc-tween-one';

import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Steps, Radio, Popover, Popconfirm } from 'antd';

import MyIcon from '@/components/MyIcon';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import StandardTable from '@/containers/StandardTable';
import StandardTableForm from '@/containers/StandardTable/StandardTableForm';
import StandardTableHandle from '@/containers/StandardTable/StandardTableHandle';

import HandleSelect from './HandleSelect';

import { bannersCenter as columns } from '@/commons/columns';
import { bannersManage as map } from '@/commons/map';
import { banners as tabList } from '@/commons/tabList';

import styles from './style.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, row = {}, form, handleUpdate, handleModalVisible } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleUpdate(fieldsValue);
    });
  };

  return (
    <Modal
      destroyOnClose
      width={1300}
      visible={modalVisible}
      footer={null}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <HandleSelect />
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ bannerManage, loading }) => ({
  bannerManage,
  loading: loading.models.bannerManage,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    row: {},
  };

  columns = [...columns, {
    title: '操作',
    width: 99,
    align: 'center',
    fixed: 'right',
    render: payload => (
      <Popconfirm title="确认删除?" onConfirm={this.handleRemove.bind(null, payload)} okText="确认" cancelText="取消">
        <Button icon="delete" type="primary" ghost size="small">
          {payload.type === 0 ? '从首页删除' : payload.type === 1 ? '从详情删除' : 'O(∩_∩)O'}
        </Button>
      </Popconfirm>
    )
  }];

  tabList = [...tabList];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'bannerManage/fetch'
    });
  }

  handleTabChange = type => {
    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'bannerManage/fetch',
      payload: { type },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'bannerManage/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'bannerManage/fetch',
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'bannerManage/remove',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              dispatch({
                type: 'bannerManage/fetch'
              });
              this.setState({
                selectedRows: []
              });
              message.success(`共有${data}条广告删除成功~`);
            } else {
              message.error('删除失败！');
            }
          },
        });
        break;
      case 'update':
        dispatch({
          type: 'bannerManage/update',
          payload: { type: 1, id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (errno) {
              message.error('更新失败！');
            } else {
              dispatch({
                type: 'bannerManage/fetch',
              });
              this.setState({
                selectedRows: []
              });
              message.success('更新成功！');
            }
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState(state => ({
      ...state,
      selectedRows: rows,
    }));
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        createdAt: fieldsValue.createdAt && fieldsValue.createdAt.valueOf(),
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'bannerManage/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = (flag, row) => {
    this.setState({
      modalVisible: !!flag,
      row
    });
  };

  handleRemove = payload => {
    const { dispatch } = this.props;

    dispatch({
      type: 'bannerManage/remove',
      payload,
      callback: ({ errno, data }) => {
        if (errno) {
          message.error(payload.type === 0 ? '从首页删除失败！' : payload.type === 1 ? '从详情页删除失败！' : '不清楚你在做什么');
        } else {
          dispatch({
            type: 'bannerManage/fetch'
          });
          message.success(payload.type === 0 ? '从首页删除成功！' : payload.type === 1 ? '从详情页删除成功！' : '不清楚你在做什么');
        }

        this.handleModalVisible();
      }
    });

  }

  handleUpdate = payload => {
    const { dispatch } = this.props;

    dispatch({
      type: 'bannerManage/update',
      payload,
      callback: ({ errno, data }) => {
        if (errno) {
          message.error('更新失败！');
        } else {
          dispatch({
            type: 'bannerManage/fetch'
          });
          message.success('更新成功！');
        }
      }
    });

    this.handleModalVisible();
  };

  render() {
    const {
      bannerManage: { data, type },
      loading,
      form,
    } = this.props;
    const { expandForm, row, selectedRows, modalVisible, updateModalVisible, stepFormValues } = this.state;

    const parentMethods = {
      handleUpdate: this.handleUpdate,
      handleModalVisible: this.handleModalVisible,
    };
    return (
      <PageHeaderWrapper 
        title="广告管理" 
        action={moment().format('LLLL')}
        tabList={this.tabList}
        tabActiveKey={String(type)}
        onTabChange={this.handleTabChange}
      >
        <Card bordered={false}>
          <StandardTableForm
            expandForm={expandForm}
            data={map}
            form={form}
            onSubmit={this.handleSearch}
            onReset={this.handleFormReset}
            onToggle={this.toggleForm}
          />
          <StandardTableHandle
            status={type}
            selectedRows={selectedRows}
            menuItems={{'remove': <Button type="danger" icon="delete">删除</Button>}}
            action={<Button type="primary" icon="plus" onClick={this.handleModalVisible.bind(null, true)}>选择广告</Button>}
            onMenuClick={this.handleMenuClick}
          />
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            scroll={{ x: 1300 }}
            columns={this.columns}
            expandedRowRender={record => <p style={{ marginBottom: 0 }}>备注：{record.remark}</p>}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} row={row} />
      </PageHeaderWrapper>
    );
  }
}

export default TableList;